package com.cn.aam.checaiduo.ui.homepage.pay;

import android.content.Context;
import android.content.Intent;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.cn.aam.checaiduo.AppData;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.RetrofitHome;
import com.cn.aam.checaiduo.backend.observer.OnRequestListener;
import com.cn.aam.checaiduo.backend.observer.OnRequestV2Listener;
import com.cn.aam.checaiduo.backend.rx.RxSchedulers;
import com.cn.aam.checaiduo.base.BaseActivity;
import com.cn.aam.checaiduo.base.ToolBarManager;
import com.cn.aam.checaiduo.base.web.NormalWebActivity;
import com.cn.aam.checaiduo.bean.BuyPreDataB;
import com.cn.aam.checaiduo.bean.ProductDetailB;
import com.cn.aam.checaiduo.bean.base.NormalResponseB;
import com.cn.aam.checaiduo.bean.me.VoucherB;
import com.cn.aam.checaiduo.bean.redirect.PutOrderB;
import com.cn.aam.checaiduo.minterface.MyTextWathcher;
import com.cn.aam.checaiduo.utils.MyEditTextUtils;
import com.cn.aam.checaiduo.utils.MyViewsUtils;
import com.cn.aam.checaiduo.utils.SpannableUtils;
import com.cn.aam.checaiduo.utils.StringUtil;
import com.cn.aam.checaiduo.utils.TimeUtils;
import com.cn.aam.checaiduo.widget.WMToast;

import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

import static com.cn.aam.checaiduo.Const.INTENT_REQUEST_CASH_COUPON;
import static com.cn.aam.checaiduo.Const.INTENT_REQUEST_RATE_COUPON;

/**
 * @author 微木森林
 * @time 2017/6/1 下午4:01
 * @description 订单支付
 * @remark
 */
public class BuyProductConfirmActivity extends BaseActivity {
    private final static String DATA_PRODUCT_DETAIL = "data_product_detail";

    @BindView(R.id.tv_sequence)
    TextView tvSequence;
    @BindView(R.id.tv_left_amount)
    TextView tvLeftAmount;
    @BindView(R.id.et_invest_amount)
    EditText etInvestAmount;
    @BindView(R.id.tv_invest_amount)
    TextView tvInvestAmount;

    @BindView(R.id.cb_balance)
    CheckBox cbBalance;//使用余额

    @BindView(R.id.tv_value_balance)
    TextView tvValueBalance;//余额
    @BindView(R.id.tv_value_coupon_crash)
    TextView tvValueCouponCrash;//现金券
    @BindView(R.id.tv_value_coupon_rate)
    TextView tvValueCouponInterest;//加息券

    @BindView(R.id.cb_protocol)
    CheckBox cbProtocol;//协议

    @BindView(R.id.tv_target_coupon_crash)
    TextView tvTargetCouponCrash;//所选的现金券
    @BindView(R.id.tv_target_coupon_rate)
    TextView tvTargetCouponRate;//所选的加息券
    @BindView(R.id.tv_protocol)
    TextView tvProtocol;


    private VoucherB.CashCouponBean cashCoupon;//现金券
    private VoucherB.RateCouponBean rateCoupon;//加息券
    private int chooseCashIndex = -1, chooseRateIndex = -1;


    private VoucherB allCoupon;//所有的卡券
    private ProductDetailB detailData;
    private BuyPreDataB buyPreData;

    //提交订单所需参数
    private String token;
    private String id;
    private String amount;
    private boolean isUseBalance = false;
    private String cashCouponID;
    private String rateCouponID;


    public static Intent newInstance(Context context, ProductDetailB productDetail) {
        Intent intent = new Intent(context, BuyProductConfirmActivity.class);
        intent.putExtra(DATA_PRODUCT_DETAIL, productDetail);
        return intent;
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_buy_product_confirm;
    }

    @Override
    protected void onGenerate() {
        initData();
        getAllCoupon();
    }

    private void initData() {
        detailData = (ProductDetailB) getIntent().getSerializableExtra(DATA_PRODUCT_DETAIL);
        token = AppData.getToken();
        id = detailData.getId();
    }


    private void getAllCoupon() {
        //get all coupon
        RetrofitHome.getInstance()
                .getInternalApi()
                .getPreInvestData(token, id)
                .compose(RxSchedulers.<NormalResponseB<BuyPreDataB>>toMain())
                .subscribe(new OnRequestV2Listener<BuyPreDataB>(this) {
                    @Override
                    public void onNext(NormalResponseB<BuyPreDataB> value) {
                        super.onNext(value);
                        if (value.getIsLogged() != Const.STATE_LOGIN) {
                            goLogin();
                            return;
                        }
                        if (value.getCode() == Const.REQUEST_SUCCESS && value.getData() != null)
                            renderCoupon(buyPreData = value.getData());
                    }
                });
    }


    private void renderCoupon(BuyPreDataB data) {
        //two coupon list
        allCoupon = new VoucherB(data.getCash_coupon(), data.getRate_coupon());
        //left money
        MyViewsUtils.showAllViews(tvLeftAmount);
        tvLeftAmount.setText("订单剩余：" + data.getLeft_amount() + "元");
        //balance
        tvValueBalance.setText("（可用：" + StringUtil.dealDataEnd(data.getAvailable_amount() + "") + "元）");
        //cash coupon
        tvValueCouponCrash.setText("(余量 ：" + allCoupon.getCash_coupon().size() + "张)");
        //rate coupon
        tvValueCouponInterest.setText("(余量 ：" + allCoupon.getRate_coupon().size() + "张)");
        //check box balance
        cbBalance.setChecked(false);
    }


    @Override
    protected void initView() {
        //toolbar
        ToolBarManager.with(this, WMContent)
                .setBackgroundColor(R.color.toolbar_bg_grey)
                .setNavigationIcon(R.drawable.ic_nav_arrow_back)
                .setTitle("订单支付")
                .setTitleColor(R.color.black_normal);

        //sequence
        tvSequence.setText("第" + detailData.getSequence() + "期");

        //left money
        MyViewsUtils.hideAllViews(tvLeftAmount);

        //edit invest amount
        etInvestAmount.addTextChangedListener(new MyTextWathcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setCashCouoponNull();
                String str = s.toString();
                if (str.length() > 18) {
                    etInvestAmount.setText(str.substring(0, str.length() - 1));
                    MyEditTextUtils.setSeletionEnd(etInvestAmount);

                    return;
                }
                if (TextUtils.isEmpty(str) || str.charAt(0) == '.') {
                    tvInvestAmount.setText("0元");
                    return;
                }

                tvInvestAmount.setText(str + "元");
            }
        });

        //tv protocol
        SpannableStringBuilder strSpan = new SpannableStringBuilder("我已阅读并同意《悟空车服务协议》");
        SpannableUtils.NoLineSpan noLineSpan = new SpannableUtils.NoLineSpan(mContext) {
            @Override
            public void onClick(View widget) {
                //《悟空车服务协议》

                String url = RetrofitHome.HOST_API + "wap/Usercenter/serviceAgreement";
                startActivity(NormalWebActivity.newInstance(mContext, url, "悟空车服务协议"));
            }
        };
        strSpan.setSpan(noLineSpan, 7, tvProtocol.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvProtocol.setText(strSpan);
        tvProtocol.setMovementMethod(LinkMovementMethod.getInstance());//必须设置才能点击
    }

    @OnCheckedChanged(R.id.cb_balance)
    public void onBalanceChange(boolean isUserBalance) {
        if (buyPreData == null) return;
        if (isUserBalance) {
            if (buyPreData.getAvailable_amount() != 0)
                etInvestAmount.setText(buyPreData.getAvailable_amount() + "");
        } else {
            etInvestAmount.setText("");
        }
        MyEditTextUtils.setSeletionEnd(etInvestAmount);

    }

    /**
     * 获取所需的所有值
     */
    public void getAllValue() {
        token = AppData.getToken();
        id = detailData.getId();
        amount = MyEditTextUtils.getContent(etInvestAmount);
        isUseBalance = cbBalance.isChecked();
        cashCouponID = cashCoupon == null ? null : cashCoupon.getId();
        rateCouponID = rateCoupon == null ? null : rateCoupon.getId();
    }

    /**
     * 提交订单前的检查
     *
     * @return
     */
    private boolean checkAllStatus() {
        getAllValue();
        if (!cbProtocol.isChecked()) {
            WMToast.normal("请先阅读《悟空车服务协议》");
            return false;
        }
        if (amount.startsWith(".")) {
            WMToast.normal("金额格式有误");
            return false;
        }
        if (TextUtils.isEmpty(amount)) {
            WMToast.normal("投资本金不能为0元");
            return false;
        }
        //【逻辑】1000元以下，必须付全部余额
        if (Double.parseDouble(detailData.getLeft_amount()) <= 1000 && Double.parseDouble(amount) < Double.parseDouble(detailData.getLeft_amount())) {
            etInvestAmount.setText(detailData.getLeft_amount());
            MyEditTextUtils.setSeletionEnd(etInvestAmount);
            WMToast.normal("订单剩余少于等于1000元，必须使用所有余额投资");
            return false;
        }
        if (Double.parseDouble(detailData.getLeft_amount()) > 1000 && Double.parseDouble(amount) < 1000) {
            WMToast.normal("投资本金金额不少于1000元");
            return false;
        }
        //当前金额大于可投资金额
        if (Double.parseDouble(MyEditTextUtils.getContent(etInvestAmount)) > Double.parseDouble(detailData.getLeft_amount())) {
            etInvestAmount.setText(detailData.getLeft_amount());
            MyEditTextUtils.setSeletionEnd(etInvestAmount);
            WMToast.normal("当前金额大于可投资金额");
            return false;
        }
        //【逻辑】15万以内的标的开投10分钟之内每次最多只能投3000元
        if (getRaiseAmount(detailData.getRaise_amount()) <= 15) {
            //2017-06-01 17:00:00
            String startTime = detailData.getStart_time();
            //startTime = "2017-07-03 16:45:00";
            Date startDate = TimeUtils.String2Date(startTime, TimeUtils.DATE_FORMAT_TYPE_01);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            calendar.add(Calendar.MINUTE, +10);
            Date dateLine = calendar.getTime();//10分钟后的时间
            Date currentDate = new Date();

            boolean isIn10Minutes = currentDate.compareTo(dateLine) <= 0;
            if (isIn10Minutes && Double.parseDouble(amount) > 3000) {
                WMToast.longToast("15万以内的标的开投10分钟之内每次最多只能投3000元");
                return false;
            }
        }
        return true;
    }


    /**
     * 获取double类型的项目总额
     */
    private Double getRaiseAmount(String raiseAmount) {
        return Double.parseDouble(raiseAmount.replace("万", ""));
    }


    /**
     * 立即下单
     */
    @OnClick(R.id.btn_submit)
    public void onClickToPay() {
        if (!checkAllStatus())
            return;
        //postOrder

        if (MyViewsUtils.isFastDoubleClick()) {
            return;
        }
        RetrofitHome.getInstance()
                .getInternalApi()
                .postOrder(token, id, amount, "" + (isUseBalance ? 1 : 0), cashCouponID, rateCouponID)
                .compose(RxSchedulers.<PutOrderB>toMain())
                .subscribe(new OnRequestListener<PutOrderB>(this) {

                    @Override
                    protected String getProgressBarContent() {
                        return "跳转中...";
                    }

                    @Override
                    public void onNext(PutOrderB value) {
                        super.onNext(value);
                        if (value.getCode() == Const.REQUEST_SUCCESS)
                            startActivityForResult(PayActivity.newInstance(mContext, value.getRedirect_content(), "订单支付", value.getOrder_id()), Const.INTENT_REQUEST_PAY_ORDER);
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //付款成功
        if (requestCode == Const.INTENT_REQUEST_PAY_ORDER && resultCode == RESULT_OK) {

            finish();
        }
        //代金券
        if (requestCode == Const.INTENT_REQUEST_CASH_COUPON) {

            if (data == null)
                return;
            chooseCashIndex = data.getIntExtra("chooseIndex", -1);
            if (chooseCashIndex != -1) {
                cashCoupon = allCoupon.getCash_coupon().get(chooseCashIndex);
                tvTargetCouponCrash.setText(cashCoupon.getDescription());
            } else {
                setCashCouoponNull();
            }
        }
        //加息券
        if (requestCode == Const.INTENT_REQUEST_RATE_COUPON) {

            if (data == null)
                return;
            chooseRateIndex = data.getIntExtra("chooseIndex", -1);

            if (chooseRateIndex != -1) {
                rateCoupon = allCoupon.getRate_coupon().get(chooseRateIndex);
                tvTargetCouponRate.setText(rateCoupon.getDescription());
            } else {
                chooseRateIndex = -1;
                rateCoupon = null;
                tvTargetCouponRate.setText("");
            }
        }
    }

    private void setCashCouoponNull() {
        if (cashCoupon != null) {
            cashCoupon = null;
            tvTargetCouponCrash.setText("");
            chooseCashIndex = -1;
        }
    }

    /**
     * 代金券
     */
    @OnClick(R.id.block_coupon_cash)
    public void ChooseCouponCash() {
        startActivityForResult(ChooseVoucherActivity.newInstance(mContext, allCoupon, chooseCashIndex, ChooseVoucherActivity.CASH_COUPON, MyEditTextUtils.getContent(etInvestAmount)), INTENT_REQUEST_CASH_COUPON);
    }

    /**
     * 加息券
     */
    @OnClick(R.id.block_coupon_interest)
    public void ChooseCouponInterest() {
        startActivityForResult(ChooseVoucherActivity.newInstance(mContext, allCoupon, chooseRateIndex, ChooseVoucherActivity.RATE_COUPON, MyEditTextUtils.getContent(etInvestAmount)), INTENT_REQUEST_RATE_COUPON);
    }

}
